package com.codeoss.framework.view.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.converter.IConverter;
import com.codeoss.framework.converter.IConverterStore;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.util.LookupInfo;
import com.codeoss.framework.util.StringUtils;
import com.codeoss.framework.view.clientscript.MListViewAddRowClientScript;
import com.codeoss.framework.view.clientscript.MListViewRemoveRowClientScript;
import com.codeoss.framework.view.clientscript.MListViewUpdateRowClientScript;
import com.codeoss.framework.view.component.Component;
import com.codeoss.framework.view.component.IDataBindSource;
import com.codeoss.framework.view.component.IDataBinding;
import com.codeoss.framework.view.component.IDataType;
import com.codeoss.framework.view.component.ILookup;
import com.codeoss.framework.view.component.Page;
import com.codeoss.framework.view.component.mobile.MListView;
import com.codeoss.framework.view.component.store.IComponentStore;
import com.codeoss.framework.view.datasource.DataSourceConfig;
import com.codeoss.framework.view.datasource.IDataSource;
import com.codeoss.framework.view.datasource.store.IDataSourceStore;
import com.codeoss.framework.view.model.SelectItem;
import com.codeoss.framework.view.pagebean.base.BaseFormViewPageBean;
import com.codeoss.framework.view.util.DataSourceUtil;
import com.codeoss.framework.view.util.LookupUtil;

@Service("mlistviewComponentService")
public class MListViewComponentService extends ContainerService {
	@Autowired
	private IComponentStore componentStore;
	@Autowired
	private IConverterStore converterStore;
	@Autowired
	private ITableStore tableStore;
	@Autowired
	private LookupUtil lookupUtil;
	@Autowired
	private IDataSourceStore dataSourceStore;
	@Autowired
	private BaseFormViewPageBean baseFormViewPageBean;
	@Autowired
	private DataSourceUtil dataSourceUtil;
	@Override
	public void processEvent(YunContext yunContext, Component component, String eventType) {
		// TODO Auto-generated method stub
		super.processEvent(yunContext, component, eventType);
		MListView mListView = (MListView) component;
		if ("detailOK".equals(eventType)) {
			Page formPage = componentStore.get(mListView.getFormPageCode());
			List<IDataBinding> dataBindingList = formPage.getAttribute("key_form_field_list");
			Map<String, Object> dataMap = new HashMap<String, Object>();
			Table table = null;
			for (int i = 0; i < dataBindingList.size(); i++) {
				IDataBinding dataBinding = dataBindingList.get(i);
				if (i == 0) {
					DataSourceConfig dataSourceConfig = dataSourceUtil.getDataSourceConfigById(formPage,
							((IDataBindSource) dataBinding).getDataSource());
					table = tableStore.get(dataSourceConfig.getTableName());
				}
				String sValue = yunContext.getViewRequest().getData().get(((Component) dataBinding).getId());
				if (!StringUtils.isEmpty(sValue)) {
					Column column = table.getColumnByColumnName(((IDataBinding) dataBinding).getDataField());
					IConverter converter = converterStore.getConverter(column.getDataType());
					Object value = converter.convertStringToObject(sValue);
					dataMap.put(((IDataBinding) dataBinding).getDataField(), value);
				} else {
					dataMap.put(((IDataBinding) dataBinding).getDataField(), null);
				}
			}
			List<IDataBinding> dataBindingList2 = yunContext.getPage()
					.getAttribute("key_listview_field_list" + mListView.getId());
			DataSourceConfig dataSourceConfig2 = dataSourceUtil.getDataSourceConfigById(yunContext.getPage(),
					mListView.getDataSource());
			Table table2 = tableStore.get(dataSourceConfig2.getTableName());
			Map<String, List<SelectItem>> selectItemMap = new HashMap<String, List<SelectItem>>();
			dataMap.put("selectItemMap", selectItemMap);
			for (int j = 0; j < dataBindingList2.size(); j++) {
				IDataBinding dataBinding2 = dataBindingList2.get(j);
				Column column = table2.getColumnByColumnName(dataBinding2.getDataField());
				((IDataType) dataBinding2).setDataType(column.getDataType());
				if (dataBinding2 instanceof ILookup) {
					LookupInfo lookupInfo = ((ILookup) (dataBinding2)).getLookupInfo();
					if (lookupInfo != null) {
						List<SelectItem> selectItemList = lookupUtil.getSelectItemList(yunContext, lookupInfo);
						if (selectItemList != null) {
							selectItemMap.put(component.getId(), selectItemList);
						}
					}
				}
			}
			boolean isNew = "true".equals(yunContext.getViewRequest().getData().get(mListView.getId() + "__isnew"));
			if (isNew) {
				MListViewAddRowClientScript mListViewAddRowClientScript = new MListViewAddRowClientScript();
				mListViewAddRowClientScript.setListViewId(mListView.getId());
				mListViewAddRowClientScript.setData(dataMap);
				yunContext.addClientScript(mListViewAddRowClientScript);
				yunContext.setRenderCompleted(true);
			}else {
				MListViewUpdateRowClientScript mListViewUpdateRowClientScript = new MListViewUpdateRowClientScript();
				mListViewUpdateRowClientScript.setListViewId(mListView.getId());
				mListViewUpdateRowClientScript.setData(dataMap);
				yunContext.addClientScript(mListViewUpdateRowClientScript);
				yunContext.setRenderCompleted(true);
			}
		} else if ("removeRowEvent".equals(eventType)) {
			deleteRow(yunContext, component);

			MListViewRemoveRowClientScript mListViewRemoveRowClientScript = new MListViewRemoveRowClientScript();
			mListViewRemoveRowClientScript.setListViewId(component.getId());

			yunContext.addClientScript(mListViewRemoveRowClientScript);
			yunContext.setRenderCompleted(true);
		}else if ("paginationEvent".equals(eventType)) {
			Expression onPagination = mListView.getOnPagination();
			if (onPagination != null) {
				executeEventExpression(yunContext, component, onPagination,null);
			}
		}
	}

	protected void deleteRow(YunContext yunContext, Component component) {
		MListView mListView = (MListView) component;
		DataSourceConfig dataSourceConfig = dataSourceUtil.getDataSourceConfigById(yunContext.getPage(),
				mListView.getDataSource());
		String sId = yunContext.getViewRequest().getData().get("id");
		if (!StringUtils.isEmpty(sId)) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			com.codeoss.framework.data.metadata.Table table=tableStore.get(dataSourceConfig.getTableName());
			Column keyColumn=table.getPrimaryKeyColumn();
			IConverter converter=converterStore.getConverter(keyColumn.getDataType());
			dataMap.put("id",converter.convertStringToObject(sId));
			IDataSource dataSource=dataSourceStore.getDataSource(table.getAccessType());
			dataSource.delete(yunContext, table, dataMap);
			baseFormViewPageBean.saveParentFormulaAndSummaryField();
		}
	}
}
